import { Module } from 'vuex'
import { ILoginState } from './type'
import { IRootState } from '../type'
import router from '@/router/index'

import { getToken, getUserInfoById, getMenuById } from '@/service/login/login'
import localCatch from '@/utils/setCatch'
import mapMenuToRoutes, { mapToPermission } from '@/utils/mapMenus'
const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      menuList: [],
      allPermission: []
    }
  },
  mutations: {
    changeToken(state, payload) {
      state.token = payload
    },
    setUserInfo(state, payload) {
      state.userInfo = payload
    },
    setMenuList(state, payload) {
      state.menuList = payload
    },
    setAllPermission(state, payload) {
      state.allPermission = payload
    },
    loadLocalLogin(state) {
      const JSONToken = localStorage.getItem('token')
      if (JSONToken) {
        const token = JSONToken.substring(1, JSONToken.length - 1)
        state.token = token
      }
      const userInfo = localCatch.getCatch('userinfo')
      if (userInfo) {
        state.userInfo = userInfo
      }
      const menu = localCatch.getCatch('menu')
      if (menu) {
        state.menuList = menu
        const activeRoutes = mapMenuToRoutes(menu)
        activeRoutes.forEach((route) => {
          router.addRoute('main', route)
        })
      }
      const permissions = localCatch.getCatch('allPermission')
      if (permissions) {
        state.allPermission = permissions
      }
    }
  },
  actions: {
    async getTokenAction({ commit }, payload: any) {
      // 1.获取token并保存
      const { data } = await getToken(payload)
      commit('changeToken', data.token)
      localCatch.setCatch('token', data.token)
      // 2.获取用户信息
      const userRes = await getUserInfoById(data.id)
      commit('setUserInfo', userRes.data)
      localCatch.setCatch('userinfo', userRes.data)
      // 3.获取菜单，并动态生成路由
      const menuRes = await getMenuById(userRes.data.role.id)
      commit('setMenuList', menuRes.data)
      localCatch.setCatch('menu', menuRes.data)
      // 4.根据菜单获取权限
      const allPermission = mapToPermission(menuRes.data)
      localCatch.setCatch('allPermission', allPermission)
      commit('setAllPermission', allPermission)

      router.push('/main')
    }
  }
}

export default loginModule
